from flask import Flask, render_template, request, session, redirect, url_for, jsonify
import os
import random

app = Flask(__name__)
app.secret_key = os.urandom(24)

#riddles生成
def set_pull_riddles():
    riddles=[]
    list1=os.listdir('./static//riddles')
    for i in list1:
        riddle={
            'image': i,
            'answer':os.path.splitext(i)[0]  # 使用strip()同时去除首尾空格和换行符
        }
        riddles.append(riddle)
    return riddles
values=set_pull_riddles()
def set_push_riddles():
    global values  # 使用全局变量values
    return random.sample(values, 10)
'''
riddles = [
    {'image': 'riddle1.jpg', 'answer': '画蛇添足'},
    {'image': 'riddle2.jpg', 'answer': '井底之蛙'},
    {'image': 'riddle3.jpg', 'answer': '守株待兔'},
]
'''
@app.route('/')
def index():
    session.clear()
    session['current_index'] = 0
    session['score'] = 0
    session['riddles'] = set_push_riddles()
    return redirect(url_for('game'))

@app.route('/game')
def game():
    if 'current_index' not in session:
        return redirect(url_for('index'))
    
    current_index = session['current_index']
    return render_template('game.html',
                         riddle=session['riddles'][current_index],
                         current_index=current_index,
                         total_riddles=len(session['riddles']),
                         score=session['score'])

@app.route('/check_answer', methods=['POST'])
def check_answer():
    if 'current_index' not in session:
        return jsonify({'error': '会话已过期'}), 401
    
    user_answer = request.form.get('answer', '').strip()
    correct_answer = session['riddles'][session['current_index']]['answer']
    
    response_data = {
        'score': session['score'],
        'current_index': session['current_index'],
        'total_riddles': len(session['riddles'])
    }
    
    if user_answer == correct_answer:
        session['score'] += 10
        response_data['correct'] = True
        response_data['score'] = session['score']
    else:
        response_data.update({
            'correct': False,
            'correct_answer': correct_answer
        })
    
    session.modified = True
    return jsonify(response_data)

@app.route('/next_question', methods=['POST'])
def next_question():
    try:
        if 'current_index' not in session:
            return jsonify({'error': '会话已过期'}), 401
            
        total = len(session['riddles'])
        new_index = (session['current_index'] + 1) % total
        session['current_index'] = new_index
        session.modified = True

        return jsonify({
            'image_url': url_for('static', filename=f'riddles/{session["riddles"][new_index]["image"]}'),
            'current_index': new_index,
            'score': session['score'],
            'total_riddles': total
        })
        
    except Exception as e:
        return jsonify({'error': f'加载失败: {str(e)}'}), 500

@app.route('/submit', methods=['POST'])
def submit():
    if 'score' not in session:
        return jsonify({'error': '会话已过期'}), 401
    
    final_score = session['score']
    session.clear()
    return jsonify({'score': final_score})

@app.route('/finish')
def finish():
    score = request.args.get('score', 0)
    return render_template('finish.html', score=score)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
